<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="8">
        <!-- 个人信息卡片 -->
        <el-card class="profile-card">
          <div class="avatar-wrapper">
            <el-avatar 
              :size="120" 
              :src="userInfo?.avatar || avatarUrl" 
              @error="handleAvatarError"
            >
              {{ userInfo?.nickname?.[0]?.toUpperCase() || 'U' }}
            </el-avatar>
            <div class="avatar-actions">
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :data="uploadData"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :on-error="handleUploadError"
                :before-upload="beforeAvatarUpload"
              >
                <el-button type="primary" size="small">更换头像</el-button>
              </el-upload>
            </div>
          </div>
          <div class="info-display">
            <h2>{{ userInfo?.nickname || userInfo?.username }}</h2>
            <p>ID: {{ userInfo?.id }}</p>
            <p>{{ userInfo?.email }}</p>
            <el-tag v-if="userInfo?.goal" :type="goalTypeMap[userInfo.goal]">
              {{ goalTextMap[userInfo.goal] }}
            </el-tag>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="24" :md="16">
        <!-- 基本信息表单 -->
        <el-card class="info-form-card">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
              <el-button type="primary" @click="handleSave" :loading="loading">
                保存修改
              </el-button>
            </div>
          </template>
          
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
            class="profile-form"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" disabled />
            </el-form-item>
            
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="form.nickname" placeholder="请输入昵称" />
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
            
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="form.gender">
                <el-radio :value="'male'">男</el-radio>
                <el-radio :value="'female'">女</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="生日" prop="birthday">
              <el-date-picker
                v-model="form.birthday"
                type="date"
                placeholder="选择生日"
                :disabled-date="disabledDate"
              />
            </el-form-item>
            
            <el-form-item label="身高(cm)" prop="height">
              <el-input-number
                v-model="form.height"
                :min="100"
                :max="250"
                :precision="1"
              />
            </el-form-item>
            
            <el-form-item label="体重(kg)" prop="weight">
              <el-input-number
                v-model="form.weight"
                :min="30"
                :max="200"
                :precision="1"
              />
            </el-form-item>
            
            <el-form-item label="活动水平" prop="activityLevel">
              <el-radio-group v-model="form.activityLevel">
                <el-radio-button :value="'sedentary'">久坐不动</el-radio-button>
                <el-radio-button :value="'lightly_active'">轻度活动</el-radio-button>
                <el-radio-button :value="'moderately_active'">中度活动</el-radio-button>
                <el-radio-button :value="'very_active'">重度活动</el-radio-button>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="健康目标" prop="goal">
              <el-select v-model="form.goal" placeholder="请选择健康目标">
                <el-option label="减重" value="lose_weight" />
                <el-option label="保持体重" value="maintain" />
                <el-option label="增肌" value="gain_muscle" />
              </el-select>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 修改密码卡片 -->
        <el-card class="password-card">
          <template #header>
            <div class="card-header">
              <span>修改密码</span>
              <el-button type="primary" @click="handleChangePassword" :loading="passwordLoading">
                确认修改
              </el-button>
            </div>
          </template>
          
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="100px"
          >
            <el-form-item label="当前密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                show-password
                placeholder="请输入当前密码"
              />
            </el-form-item>
            
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                show-password
                placeholder="请输入新密码"
              />
            </el-form-item>
            
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                show-password
                placeholder="请再次输入新密码"
              />
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const store = useStore()
const formRef = ref(null)
const passwordFormRef = ref(null)
const loading = ref(false)
const passwordLoading = ref(false)
const router = useRouter()

const userInfo = computed(() => store.state.user.userInfo)
const avatarUrl = computed(() => {
  const userId = store.state.user.userId
  if (!userId) return ''
  return `${process.env.VUE_APP_API_URL || ''}/api/user/avatar?userId=${userId}&t=${Date.now()}`
})

// 目标类型映射
const goalTypeMap = {
  'lose_weight': 'danger',
  'maintain': 'warning',
  'gain_muscle': 'success'
}

const goalTextMap = {
  'lose_weight': '减重',
  'maintain': '保持',
  'gain_muscle': '增肌'
}

// 表单数据
const form = reactive({
  id: '',
  profileId: '',
  nickname: '',
  gender: '',
  age: '',
  height: 170,
  weight: 60,
  activityLevel: 'lightly_active'
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  birthday: [
    { required: true, message: '请选择生日', trigger: 'change' }
  ],
  height: [
    { required: true, message: '请输入身高', trigger: 'blur' }
  ],
  weight: [
    { required: true, message: '请输入体重', trigger: 'blur' }
  ],
  activityLevel: [
    { required: true, message: '请选择活动水平', trigger: 'change' }
  ],
  goal: [
    { required: true, message: '请选择健康目标', trigger: 'change' }
  ]
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' }
  ]
}

// 上传相关配置
const uploadUrl = '/api/user/avatar'
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${localStorage.getItem('token')}`
}))
const uploadData = computed(() => ({
  userId: store.state.user.userId
}))

// 头像上传成功处理
const handleAvatarSuccess = (response) => {
  if (response?.code === 200 || response?.success) {
    // 更新用户信息以获取新的头像URL
    store.dispatch('user/getUserInfo')
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response?.message || '上传失败')
  }
}

// 头像加载失败处理
const handleAvatarError = () => {
  console.warn('头像加载失败，使用默认头像')
}

// 头像上传失败处理
const handleUploadError = (error) => {
  console.error('头像上传失败:', error)
  ElMessage.error('头像上传失败，请重试')
}

// 上传前的验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

// 日期限制
const disabledDate = (time) => {
  return time.getTime() > Date.now()
}

// 保存基本信息
const handleSave = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      try {
        loading.value = true
        // 确保传递 id
        const formData = {
          ...form,
          id: form.id || localStorage.getItem('userId')
        }
        await store.dispatch('user/updateUserInfo', formData)
        ElMessage.success('保存成功')
      } catch (error) {
        console.error('保存失败:', error)
        if (error.response?.data?.message) {
          ElMessage.error(error.response.data.message)
        } else {
          ElMessage.error(error.message || '保存失败')
        }
      } finally {
        loading.value = false
      }
    }
  })
}

// 修改密码
const handleChangePassword = () => {
  passwordFormRef.value.validate(async valid => {
    if (valid) {
      try {
        passwordLoading.value = true
        await store.dispatch('user/updatePassword', passwordForm)
        ElMessage.success('密码修改成功')
        passwordForm.oldPassword = ''
        passwordForm.newPassword = ''
        passwordForm.confirmPassword = ''
      } catch (error) {
        console.error('密码修改失败:', error)
      } finally {
        passwordLoading.value = false
      }
    }
  })
}

// 初始化表单数据
onMounted(async () => {
  try {
    const userId = localStorage.getItem('userId')
    if (!userId) {
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }

    if (!userInfo.value) {
      await store.dispatch('user/getUserInfo')
    }

    if (userInfo.value) {
      Object.assign(form, {
        id: userInfo.value.id,
        profileId: userInfo.value.profileId,
        nickname: userInfo.value.nickname,
        gender: userInfo.value.gender,
        age: userInfo.value.age,
        height: userInfo.value.height,
        weight: userInfo.value.weight,
        activityLevel: userInfo.value.activityLevel || 'lightly_active'
      })
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败，请重新登录')
    router.push('/login')
  }
})
</script>

<style lang="scss" scoped>
.profile-container {
  padding: 20px;
  
  .profile-card {
    margin-bottom: 20px;
    
    .avatar-wrapper {
      text-align: center;
      margin-bottom: 20px;
      
      .el-avatar {
        background-color: var(--el-color-primary);
        color: #fff;
        font-size: 24px;
        font-weight: bold;
      }
      
      .avatar-actions {
        margin-top: 16px;
      }
    }
    
    .info-display {
      text-align: center;
      
      h2 {
        margin: 0 0 8px;
      }
      
      p {
        margin: 0 0 16px;
        color: var(--el-text-color-secondary);
      }
    }
  }
  
  .info-form-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .profile-form {
      max-width: 600px;
    }
  }
  
  .password-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .el-form {
      max-width: 600px;
    }
  }
}

.avatar-uploader {
  text-align: center;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style> 